<?php

namespace Cyfy\Modules\QuickLinks;


/**
 * QuickLinks is a module for creating small blocks with header and hypertext link.
 * It's ideal for putting into columns / menus.
 *
 * @version 1.0
 * @author Dandelion
 */ 
class Module extends \Cyfy\Module
{
	/**
	 * Administration method, if parameter $name NOT called, returns array with possible choices.
	 * If $name called, it returns string with administration interface.
	 *
	 * @param string Name of the interface
	 * @return mixed Array with names or string with interface
	 */
	static function administration($name = "")
	{
		if($name != "")
		{
			$output = "<div id=\"AdminListOfQuickLinks\">" . self :: listOfLinks() . "</div>\n";
			$output .= "<div id=\"AdminEditQuickLink\"></div>\n";
			$output .= "<h2>" . self :: t(80) . "</h2>\n";
			$form = new Forms\Create();
			$output .= $form -> show();
			return $output;
		}
		else
		{
			return array(
				"quicklinks" => array("name" => self :: t(10), "description" => self :: t(20), "permission" => "create and edit links")
			);
		}	
	}
	
	/**
	 * AJAX method, returns result of AJAX call.
	 *
	 * @param string Name if the AJAX method.
	 * @return mixed String or array on success, False on fail.
	 */
	static function ajax($name)
	{
		// if no permission - return false
		if(!\Cyfy\Cyfy ::  permission("QuickLinks", "create and edit links"))
		{   
            \Cyfy\Cyfy ::  noPermission();
			return false;
		}
	
		// else continue
		switch($name)
		{
			case "deleteLink":
				return self :: ajaxDeleteLink($_POST['qid']);
				break;
	
			case "editLink":
				return self :: ajaxEditLink($_POST['qid']);
				break;	
			
			case "list":
				return self :: listOfLinks();
				break;	
		}
		return false;
	}
	
	/**
	 * Block method, returns block when parameter $qcode called.
	 * If qcode not called, returns array of available blocks.
	 *
	 * @param string Code of the link
	 * @return mixed Array of blocks or content of the block
	 */
	static function blocks($qcode = "")
    {
		if($qcode)
		{
			// show block
			$result = \dibi :: query("SELECT [name], [link], [text] FROM [:cyfy:QuickLinks] WHERE [code] = %s", $qcode, ' AND excludeFrom != %s', \Cyfy\Cyfy ::  $query);
            
            // no block found, show nothing
			if(count($result) == 0)
            {
                return "";
            }   
			
            // block found
            $q = $result -> fetch();
            
            // should we use internal / external address?
            if(preg_match("/http:\/\//", $q["link"])){
                $url = $q["link"];
            }else{
                $url = \Cyfy\Cyfy ::  getPath($q["link"]);
            }
            
            // block
            $output = <<<OUTPUT

<div class="QuickLinks">
<h3>{$q["name"]}</h3>
<p><a href="{$url}">{$q["text"]}</a></p>
</div>		
            
OUTPUT;
            return $output;
        }

    // show list
        $quicklinks = array();
        $result = \dibi :: query("SELECT [code], [name] FROM [:cyfy:QuickLinks]");
        if(1)
        {
            foreach($result as $l)
            {
                $quicklinks[$l["code"]] = $l["name"]; 
            }
        }	
        return $quicklinks;
    }
	
	/**
	 * Returns list of quick links or error, if no links.
	 *
	 * @return string
	 */
	static private function listOfLinks()
	{
		$result = \dibi :: query("SELECT [qid], [name], [link], [text] FROM [:cyfy:QuickLinks]");
        if(count($result) != 0)
        {
			// some links found, create a table
			$table = new \Cyfy\Modules\Objects\Table();
			$table -> header(array( self :: t(110), self :: t(150), self :: t(30)));
		
			// rows
			foreach($result as $l)
			{
				$edit = "<input type=\"submit\" value=\"E\" onclick=\"Cyfy.ajax('QuickLinks', 'editLink', '#AdminEditQuickLink', 'qid={$l["qid"]}'); $('#AdminEditQuickLink').show();\" /> ";
				$delete = "<input type=\"submit\" value=\"X\" class=\"button-warning\" onclick=\"if(confirm('" . self :: t(41, $l["name"]) . "')){ Cyfy.ajax('QuickLinks', 'deleteLink', '#AdminListOfQuickLinks', 'qid={$l["qid"]}'); $('#AdminEditQuickLink').slideUp('fast', function(){  $(this).html('') });} return false;\" />";
				$table -> row(array($l["name"], $l["link"], $edit . $delete));
			}
			return $table -> show();
		}
		else
		{
			// no links found
			return \Cyfy\Message :: get(self :: t(50), \Cyfy\Message :: WARNING);
		}		
	}
	
	/**
	 * AJAX call for link edit.
	 *
     * @param int QuickLink ID
	 * @return Form for editing.
	 */
	static private function ajaxEditLink($qid)
	{
		$result = \dibi :: query("SELECT * FROM [:cyfy:QuickLinks] WHERE [qid] = %i", $qid);
		
		if(count($result) != 0)
		{
			// link found - get data
			$l = $result->fetch();
			
			// form
			$form = new Forms\Edit();
			$form -> setData($l);
			$form -> setTemp("oldCode", $l["code"]);
			$form -> setTemp("qid", $l["qid"]);
			
			return "<h2>" .self :: t(61, array($l["name"])) . "</h2>\n" . $form -> show();
		}
		else
		{
			return "";
		}
	}
	
	/**
	 * AJAX call for link delete.
	 *
     * @param int QuickLink ID
	 * @return List of links after deleting
	 */
	static private function ajaxDeleteLink($qid)
	{
		\dibi :: query("DELETE FROM [:cyfy:QuickLinks] WHERE [qid] = %i", $qid);
		\Cyfy\Message :: set( self :: t(70));
		return self :: listOfLinks();
	}
	
}
